package servlet;
import anno.Autowired;
import anno.RequestBody;
import anno.ResponseBody;
import com.fasterxml.jackson.core.JsonProcessingException;
import dao.ExamPaperDao;
import pojo.ExamPaper;
import utils.ApiResult;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 试卷管理Servlet
 */
@WebServlet("/paper")
public class ExamPaperServlet extends BaseServlet {

    @Autowired
    ExamPaperDao paperDao ;

    @ResponseBody
    public ApiResult create(HttpServletRequest req, HttpServletResponse resp, @RequestBody ExamPaper paper) throws SQLException, JsonProcessingException {
        paperDao.insert(paper);
        return new ApiResult(200, "创建试卷成功", null);
    }

    @ResponseBody
    public ApiResult update(HttpServletRequest req, HttpServletResponse resp, @RequestBody ExamPaper paper) throws SQLException, JsonProcessingException {
        if (paper.getPaperId() == null) {
            return new ApiResult(400, "试卷ID不能为空", null);
        }
        paperDao.update(paper);
        return new ApiResult(200, "更新试卷成功", null);
    }

    @ResponseBody
    public ApiResult delete(HttpServletRequest req, HttpServletResponse resp, String paperId) throws SQLException {
        paperDao.deleteById(Integer.valueOf(paperId));
        return new ApiResult(200, "删除试卷成功", null);
    }

    @ResponseBody
    public ApiResult findPage(HttpServletRequest req, HttpServletResponse resp, String keyword, String pageNum, String pageSize) throws SQLException {
        int page = Integer.parseInt(pageNum);
        int size = Integer.parseInt(pageSize);
        
        List<ExamPaper> papers = paperDao.findPage(page, size, keyword);
        long total = paperDao.countByKeyword(keyword);
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", papers);
        result.put("total", total);
        
        return new ApiResult(200, "查询试卷成功", result);
    }

    @ResponseBody
    public ApiResult findActivePapers(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        return new ApiResult(200, "查询可用试卷成功", paperDao.findActivePapers());
    }
}
